#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""

import os
import sys
import json
import logging
from flask import Flask, jsonify, render_template
from flask_cors import CORS
from flask import request
from flask_graphql import GraphQLView
from common.schema import schema
import requests
import config


def lambda_handler(event, context):
    # TODO implement
    operationName = event.get("operationName")
    query = event.get("query")
    if not query:
        return {
            "statusCode": 200,
            "body": json.dumps({"errors": [{"message": "请给query参数"}]})}
    variables = event.get("variables")
    headers = event.get("headers", {})
    result = schema.execute(query, variables=variables, context={"headers": headers})
    if result.errors:
        logging.exception(str(result.errors))
        errors_list = []
        for error in result.errors:

            if "Cannot query field" in str(error):
                message = "字段错误"
            # todo: 这里新增错误类型
            else:
                message = str(error.message)
            try:
                stack = str(error.stack) + "-" + str(error.message) + "-" + str(error.locations)
            except:
                stack = str(error.message)
            errors_list.append(
                {"message": message, "stack": stack})
        body = {"errors": errors_list}
    else:
        body = {"data": result.data}
    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }
    return response


def flask_handler():
    app = Flask(__name__, template_folder="pand_analyzer", static_folder="pand_analyzer")
    CORS(app, supports_credentials=True)

    name = "app_order"

    @app.route(f"/{name}/graphql_api", methods=["POST"])
    def api():
        event = request.data.decode("utf8")
        event = json.loads(event)
        event["headers"] = request.headers
        return jsonify(json.loads(lambda_handler(event, None).get("body")))

    @app.route(f"/{name}/middle_service", methods=["POST"])
    def replace_api():
        event = {}
        params = request.data.decode("utf8")
        params = json.loads(params)
        operationName = params.get("operationName")
        params_str = json.dumps(params)
        event["query"] = f"query {operationName}($condition:{operationName}_argument)" + "{" + \
                         f"{operationName}(condition:$condition)" + "{ret}" \
                         + "}"
        event["variables"] = {"condition": {"args": params_str}}
        event["operationName"] = operationName
        event["headers"] = request.headers

        return jsonify(json.loads(lambda_handler(event, None).get("body")))

    app.add_url_rule(f'/{name}/graphql_doc_ui', view_func=GraphQLView.as_view('graphql',
                                                                              schema=schema, graphiql=True))

    @app.route(f"/{name}/pand_analyzer/", methods=["GET"])
    def index():
        return render_template("index.html")

    @app.route(f"/{name}/search/", methods=["POST"])
    def app_order():
        params = json.loads(request.data.decode("utf8"))
        phone = params.get("phone")
        page = params.get("body").get("page")
        pagesize = params.get("body").get("pagesize")
        url = config.es_cluster[
                  0] + config.app_order_dataset + f"/_search?q=phone.keyword:{phone}&size={pagesize}&from={(page - 1) * pagesize}&sort=gettime:asc"
        res = requests.get(url).json()
        data = res.get("hits", {}).get("hits", [])
        total = res.get("hits", {}).get("total", 0)
        result = []
        for j in data:

            i = j.get("_source", {})
            if i.get("orderstatusname") == "已完成":
                orderstatus = "1070"
            else:
                orderstatus = "1091"
            m = {
                "accountcost": i.get("accountcost"),
                "createtime": i.get("gettime"),
                "customername": i.get("phone"),
                "getstation": {
                    "avlvehiclenum": 53,
                    "id": 80,
                    "latitude": 29.629309,
                    "longtitude": 106.498057,
                    "parkingnum": 100,
                    "pilenum": 0,
                    "stationaddress": i.get("getstationname"),
                    "stationname": i.get("getstationname"),
                    "vehiclenum": 54
                },
                "getstationname": i.get("getstationname"),
                "gettime": i.get("gettime"),
                "modifytime": i.get("gettime"),
                "orderid": 6620106,
                "orderno": i.get("orderno"),
                "orderstatus": orderstatus,
                "orderstatusname": i.get("orderstatusname"),
                "payTypeName": "",
                "payedamount": i.get("accountcost"),
                "paytype": 1100,
                "realgettime": i.get("gettime"),
                "realrettime": i.get("rettime"),
                "reduceFeeAmount": 0,
                "rentAmount": i.get("accountcost"),
                "rentAmountNew": i.get("accountcost"),
                "rentaltypename": i.get("rentaltypename"),
                "retstation": {
                    "avlvehiclenum": 53,
                    "id": 80,
                    "latitude": 29.629309,
                    "longtitude": 106.498057,
                    "parkingnum": 100,
                    "pilenum": 0,
                    "stationaddress": i.get("retstationname"),
                    "stationname": i.get("retstationname"),
                    "vehiclenum": 54
                },
                "retstationname": i.get("retstationname"),
                "rettime": i.get("rettime"),
                "serviceAmount": 0,
                "serviceName": "",
                "totalamount": i.get("accountcost"),
                "vehicleid": 9676,
                "vehicletype": {
                    "doors": 5,
                    "energytypename": "纯电动",
                    "gearshiftname": "自动挡",
                    "imgurl": "https://img.pand-auto.com/2017/09/14/images/vehicle/1505383341811.png",
                    "license": i.get("license"),
                    "mileage": 180,
                    "rooms": 2,
                    "seats": 5,
                    "vehicletypeid": 50,
                    "vehicletypename": "活力熊",
                    "vehicletypepyjx": "BB"
                }
            }
            result.append(m)
        if not phone:
            return jsonify({})

        return jsonify({
            "body": {
                "orders": result,
                "totalpage": total / pagesize,
                "unCompleteOrders": []
            },
            "header": {
                "errorcode": "1000",
                "service": "getmyorder"
            }
        })

    return app


app = flask_handler()

if __name__ == '__main__':
    app.run(port=4901, debug=True, host="0.0.0.0")
